<template>
  <div class="playlist-edit mtop-20">
    <div class="font-20 font-bold">编辑歌单信息</div>
    <div class="edit-wrap mtop-20">
      <el-form class="edit-form" :model="form" label-width="80px" size="mini">
        <el-form-item label="歌单名：">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="标签：">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            clearable
            placeholder="请添加标签"
            class="tag-wrap"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介：">
          <el-input
            type="textarea"
            maxlength="1000"
            show-word-limit
            v-model="form.description"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="edit-img-container">
        <ImgCut btnText="编辑封面" :imgUrl="imgUrl" @upload="upload" />
      </div>
    </div>
    <div class="submit-wrap">
      <button
        class="btn btn-blue"
        @click="handleSave"
        :disabled="!this.form.name.trim()"
      >
        保存
      </button>
      <button class="btn btn-white" @click="$router.back()">取消</button>
    </div>
  </div>
</template>

<script>
import {
  getPlayListDetail,
  updateMyPlayList,
  uploadPlayListImg,
} from "@/api/api_playlist.js";
import ImgCut from "@/components/img-cut/ImgCut";
import { mapState } from "vuex";
export default {
  components: {
    ImgCut,
  },
  props: {
    id: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      form: {
        name: "",
        tags: [],
        description: "",
      },
      tagOptions: [
        { value: "华语", label: "华语" },
        { value: "流行", label: "流行" },
        { value: "怀旧", label: "怀旧" },
        { value: "经典", label: "经典" },
        { value: "放松", label: "放松" },
      ],
      imgUrl: "",
      isInput: false,
      defaultCoverImgUrl: require("../../assets/img/error.jpg"),
    };
  },
  watch: {
    form: {
      deep: true,
      handler(val) {
        if (val.name.length >= 20) {
          this.form.name = val.name.slice(0, 19);
          this.$message.warning("歌单名过长");
        }
        this.isInput = true;
      },
    },
  },
  created() {
    this.getPlayListInfo();
  },
  computed: {
    ...mapState(["myPlayList"]),
  },
  methods: {
    /* 获取歌单信息 */
    async getPlayListInfo() {
      let uuid = JSON.parse(localStorage.getItem("profile")).data.uuid;
      this.isLoading = true;
      const res = await getPlayListDetail(uuid,this.id);
      if (res.code !== 200) return;
      const { name, tags, description } = res.data;
      this.form = {
        name,
        tags,
        description,
      };
      this.imgUrl = res.data.coverImgUrl ? res.data.coverImgUrl : this.defaultCoverImgUrl;
      this.$nextTick(() => {
        this.isInput = false;
      });
    },
    /* 更新歌单 */
    async handleSave() {
      if (!this.isInput) {
        return this.$message.warning("并没有修改内容");
      }
      const editParams = {
        id: this.id,
        name: this.form.name,
        desc: this.form.description,
      };
      if (this.form.tags.length !== 0)
        editParams.tags = this.form.tags.join("-");//这里还是配合后端数据库tagStr来的——华语-流行-放松
      const res = await updateMyPlayList(editParams);
      if (res.code !== 200) {
        this.$message.error("更新失败");
        return;
      }
      this.$message.success("更新成功");
      this.$store.dispatch("getMyPlayList");
      this.$router.back();
    },
    /* 上传歌单封面 */
    async upload({ file }) {
      if ((file.size / Math.pow(1024.0, 2)).toFixed(2) > 1) {
        this.$message.warning("图片大小请小于 1024KB");
        return;
      }
      const formData = new FormData();
      formData.append(
        "file",
        new File([file], `playListCover.${file.type.split("/")[1]}`, {
          type: file.type,
        })
      );
      formData.append("id", this.id);
      const res = await uploadPlayListImg(formData);//{file,id}
      if (res.data.code !== 200) return this.$message.error("上传失败");
      this.$message.success("上传成功");
      this.updateUploadCover();
    },
    async updateUploadCover() {
      const res = await getPlayListDetail(this.id);
      if (res.code !== 200) return;
      const myPlayList = JSON.parse(JSON.stringify(this.myPlayList));
      const updateMyPlayList = myPlayList.map((item) => {
        if (item.id == this.id) {
          if (res.data.coverImgUrl) {
            item.picUrl = res.data.coverImgUrl;
          } else {
            item.picUrl = this.defaultCoverImgUrl;
          }
        }
        return item;
      });
      this.$store.commit("setMyPlayList", updateMyPlayList);
      this.imgUrl = res.data.coverImgUrl ? res.data.coverImgUrl : this.defaultCoverImgUrl;
    },
  },
};
</script>

<style lang="less" scoped>
.edit-form {
  width: 500px;
  @media screen and (max-width: 415px) {
    width: auto;
  }
}
.edit-wrap {
  display: flex;
  @media screen and (max-width: 415px) {
    display: block;
  }
}
.tag-wrap {
  width: 100%;
}
.edit-img-container {
  margin-left: 30px;
  @media screen and (max-width: 415px) {
    margin: 0;
  }
}
.submit-wrap {
  margin: 10px 0 0 80px;
  .btn {
    width: 80px;
    &:nth-child(2) {
      margin-left: 20px;
    }
  }
}
</style>
